package com.bl.weilan.service.biz.message.impl;

import com.bl.weilan.common.utils.Generator;
import com.bl.weilan.dao.redis.MessageDao;
import com.bl.weilan.service.biz.message.MessageService;
import com.bl.weilan.tp.submail.message.MessageApi;
import com.bl.weilan.tp.submail.message.MessageResponse;
import com.bl.weilan.tp.submail.message.MessageVars;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yujingyi on 2017/6/15.
 */
@Service
@Log4j2
public class MessageServiceImpl implements MessageService {

    final static private long CODE_VALID_DURATION = 300;
    final static private long CODE_SEND_GAP = 60;

    @Autowired
    MessageApi messageApi;

    @Autowired
    MessageDao messageDao;

    @Override
    public void sendCaptchaMessage(String mobile) {
        long expire = messageDao.getAuthCodeExpire(mobile);
        if (expire > ((CODE_VALID_DURATION - CODE_SEND_GAP) * 1000)) {
            return ;
        }

        String code = Generator.generateAuthenticationCode();
        MessageVars vars = MessageVars.builder()
                .code(code)
                .time("60秒")
                .build();
        MessageResponse messageResponse = messageApi.sendMessage(mobile, vars);

        if (messageResponse != null && messageResponse.isSuccess()) {
            messageDao.setAuthCode(mobile, code, CODE_VALID_DURATION * 1000);
        } else {
            log.error("send authentication code failed, response: {}", messageResponse);
        }

    }

}
